<?php
class KolSys_Chat
{
	const NotLoggedInRegExp='/<html>.*?<meta\s*http-equiv="Expires"\s*content="Tue, 01 Jan 2000 12:12:12 GMT">.*?<b>Not logged in.<\/b>.*?<\/html>/msi';
	public function sendMessage($text)
	{
		$bot=KolSys_Bot::getInstance();
		$pwd=$bot->pwdhash;
		$post=array('pwd'=>$pwd,'graf'=>$text);
		$response=KolSys_Nav::getPage("submitnewchat.php",array('post'=>$post));

		if(preg_match(self::NotLoggedInRegExp, $response, $matches))
		{
			echo '<span style="color:red;">Not Logged In</span>';exit;
		}
		return $response;
	}

	public function enterChat()
	{
		$response=KolSys_Nav::getPage("newchatmessages.php");
		return $response;
	}

	public function viewChatMessages($last)
	{
		global $settings;
		//$bot=Bot::getInstance();
		//$pwd=$bot->pwdhash;
		//$parameters['pwd']=$pwd;
		$debug=false;
		$FxHeaders=array('Keep-Alive: 115','Connection: keep-alive','Accept-Language: en,en-us;q=0.5','Accept-Encoding: gzip,deflate','Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7');
		$options=array('referer'=>$settings['site'].'/lchat.php','X-Requested-With'=>'XMLHttpRequest','debugMode'=>$debug,addHeaders=>$FxHeaders);
		$response=KolSys_Nav::getPage("newchatmessages.php?lasttime=$last",$options);//newchatmessages.php
		if(preg_match(self::NotLoggedInRegExp, $response, $matches))
		{
			echo '<span style="color:red;">Not Logged In</span>';exit;
		}
		return $response;
	}

	public static function extractLastSeenFromMessage($msg)
	{
		$lastSeen=false;
		if(preg_match('/<!--lastseen\:(\d+)-->/msi', $msg, $matches))
		{
			$lastSeen=$matches[1];
		}
		return $lastSeen;
	}	
	public function calcLastSeen()
	{
		global $settings;
		$lastSeen=false;
		$query="SELECT `text` FROM `chat logs` WHERE username='%s' AND `text` LIKE '%%<!--lastseen:%%-->%%' ORDER BY id desc LIMIT 1";
		$sql=KolSys_MySQLDatabase::sprintf_escape($query,$settings['kol']['username']);
		$result=KolSys_MySQLDatabase::query($sql);
		list($mostCurrentLastSeenMessage)=mysql_fetch_row($result);
		//print_r($mostCurrentLastSeenMessage);
		if(preg_match('/<!--lastseen\:(\d+)-->/msi', $mostCurrentLastSeenMessage, $matches))
		{
			$lastSeen=$matches[1];
		}
		return $lastSeen;
	}
}